/**
 * 
 */
package com.googlecode.rotools.rodb;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 
 */
public class RODBFactory {
	public RODB getRODB(String path, boolean create) throws SQLException{
		File file = new File(path);
		file.getParentFile().mkdirs();
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(
					"jdbc:derby:" + path + ";create=" + create
					);
			connection.setAutoCommit(true);
			init(connection);

			return new RODBImpl(connection);

		} catch(SQLException e) {
			if(connection != null){
				connection.close();
			}
			throw e;
		}
	}
	public void shutdownDB(String path){
		try {
			DriverManager.getConnection("jdbc:derby:" +  path + ";shutdown=true");
			
		} catch (SQLException e) {
			
		}	
	}
	private static final DefineTable DEFINE_ITEM = 
			new DefineTable(
				"ITEM", 
				"create table ITEM (" +
				"ITEM_ID VARCHAR(6), " +
				"ITEM_NAME VARCHAR(254), " +
				"ITEM_UNKNOWN_NAME VARCHAR(254), " +
				"ITEM_DESCRIPTION VARCHAR(32672), " +
				"ITEM_UNKNOWN_DESCRIPTION VARCHAR(32672), " +
				"ITEM_SLOT INTEGER, " +
				"WEAPON_LEVEL INTEGER, " +
				"WEAPON_ATK INTEGER, " +
				"GUARD_DEF INTEGER, " +
				"SLOT_COUNT INTEGER, " +
				"CARD_PREFIX VARCHAR(254), " +
				"constraint ITEM_PK primary key(ITEM_ID)" +
				")"
			);
	private void init(Connection connection) throws SQLException{
		try{
			DefineTable[] defineTables = {
					DEFINE_ITEM
			};
			for (int i = 0; i < defineTables.length; i++) {
				createTable(connection, defineTables[i]);
			}
		}finally{
			connection.commit();
		}
	}
	private void createTable(Connection connection, DefineTable defineTable) throws SQLException{
		if(!defineTable.isExist(connection)){
			defineTable.createTable(connection);
		}
	}
}

